package service

import (
	"fmt"
	"illuminant/model"
	"illuminant/util"
)

const gqlQueryUser = `query login($mobile: String!, $password: String!){
   illuminant_user(where: {mobile: {_eq: $mobile}, password: {_eq: $password}}) {
    id
    sex
    email
    mobile
    password
    username
  }
}`

const gqlGetUserByID = `query get_user_by_id($id: uuid!){
  illuminant_user_by_pk(id: $id) {
    id
    email
    mobile
    username
    password
    sex
  }
}`

const gqlUpdateUserPasswd = `mutation update_passwd($id: uuid!, $password: String!) {
  update_illuminant_user_by_pk(pk_columns: {id: $id}, _set: {password: $password}) {
    id
  }
}`

func Login(mobile, password string) *model.IlluminantUser {
	var data struct {
		Users []*model.IlluminantUser `json:"illuminant_user"`
	}

	params := map[string]interface{}{
		"mobile":   mobile,
		"password": password,
	}

	err := util.Graphql(gqlQueryUser, params, &data)
	if err != nil {
		fmt.Printf("graphql request error: %s\n", err.Error())
		return nil
	}

	if len(data.Users) > 0 {
		return data.Users[0]
	}

	return nil
}

func GetUserByID(id string) (*model.IlluminantUser, error) {
	var data struct {
		User *model.IlluminantUser `json:"illuminant_user_by_pk"`
	}

	params := map[string]interface{}{
		"id": id,
	}

	err := util.Graphql(gqlGetUserByID, params, &data)
	if err != nil {
		fmt.Printf("graphql request error: %s\n", err.Error())
		return nil, err
	}

	return data.User, nil
}

func UpdateUserPasswd(id, passwd string) (*model.IlluminantUser, error) {
	var data struct {
		User *model.IlluminantUser `json:"update_illuminant_user_by_pk"`
	}

	params := map[string]interface{}{
		"id":       id,
		"password": passwd,
	}

	err := util.Graphql(gqlUpdateUserPasswd, params, &data)
	if err != nil {
		fmt.Printf("graphql request error: %s\n", err.Error())
		return nil, err
	}

	return data.User, nil
}
